package com.yang.system.application.orgMng.orgService;

import com.yang.system.adapter.driving.persistence.orgMng.OrgRepositoryJdbc;
import com.yang.system.domain.common.exception.BusinessException;
import com.yang.system.domain.orgMng.org.Org;
import com.yang.system.domain.orgMng.org.OrgBuilder;
import com.yang.system.domain.orgMng.org.OrgHandler;
import com.yang.system.domain.orgMng.org.OrgRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrgService {

    private final OrgRepository orgRepository;
    private final OrgBuilder orgBuilder;
    private final OrgHandler orgHandler;

    @Autowired
    public OrgService(OrgRepositoryJdbc orgRepositoryJdbc,
                      OrgBuilder orgBuilder,
                      OrgHandler orgHandler) {
        this.orgBuilder = orgBuilder;
        this.orgRepository = orgRepositoryJdbc;
        this.orgHandler = orgHandler;
    }

    public OrgResponse addOrg(OrgResponse request, Long userId) {
        // 包含校验逻辑在内的创建逻辑都委托给工厂
        //Org org = orgFactory.build(request, userId);
        Org org = orgBuilder.tenantId(request.getTenantId())
                .orgTypeCode(request.getOrgTypeCode())
                .superiorId(request.getSuperiorId())
                .name(request.getName())
                .createdBy(userId)
                .build();
        org = orgRepository.save(org);
        return buildOrgDto(org);
    }

    private OrgResponse buildOrgDto(Org org) {
        // 将领域对象的值赋给DTO...
        if (org == null) {
            return null;
        }
        OrgResponse orgResponse = new OrgResponse();
        BeanUtils.copyProperties(org, orgResponse);
        orgResponse.setStatus(org.getStatus().name());
        return orgResponse;
    }


    //修改组织基本信息
    @Transactional
    public OrgResponse updateOrgBasic(Long id, OrgResponse request, Long userId) {
        Org org = (Org) orgRepository.findById(request.getTenantId(), id)
                .orElseThrow(() -> {
                    throw new BusinessException(STR."要修改的组织(id =\{id}  )不存在！");
                });
        orgHandler.updateBasic(org, request.getName()
                , request.getLeaderId(), userId);

        orgRepository.update(org);
        return buildOrgDto(org);
    }

    //取消组织
    @Transactional
    public Long cancelOrg(Long id, Long tenant, Long userId) {
        Org org = (Org) orgRepository.findById(tenant, id)
                .orElseThrow(() -> {
                    throw new BusinessException(STR."要取消的组织(id =\{id}  )不存在！");
                });
        orgHandler.cancel(org, userId);
        orgRepository.update(org);
        return org.getId();
    }
}